// subpage/pages/sitedetail/sitedetail.js
import { formatTime, formatDate } from '../../../utils/util'
import service from '../../../utils/request'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isVip: false,
    show:false,
    rate:{},
    site:{},
    baseUrl: app.data.url,
    showGunList:false,
    gunList:[],
    totalGun:0,
    showPhone: false,
    lat: '',
    lng: '',
    siteId:'',
    confirmRate: {},
    overPrice: {},
    parking:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      siteId: options.id,
      parking:options.parking,
    })
    this.nearSite()
    this.getusers()
    this.getCompanyRate(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  bandCar() {
    if (!wx.getStorageSync('token')) {
      this.isLogin();
      return;
    }
    wx.navigateTo({
      url: "/subpage/pages/carbeand/carbeand"
    })
  },
  isLogin () {
    wx.navigateTo({
			url: "/subpage/pages/login/login"
		})
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log('下拉刷新')
    this.getSite()
    this.getGunList('resh')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  phoneCall(){
    wx.makePhoneCall({
      phoneNumber: this.data.site.serviceMobile
    })
  },
   //预览图片，放大预览
   preview(event) {
    
    let currentUrl = event.target.dataset.src
    console.log(event)
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: this.data.site.pics // 需要预览的图片http链接列表
    })
  },
   //扫码
   userScen() {
    console.log('token',wx.getStorageSync('token'))
   
    // 允许从相机和相册扫码
    wx.scanCode({
      success(res) {
        console.log(res)
        let sn = res.result;
        let index = sn.lastIndexOf("\=");
        sn = sn.substring(index + 1, sn.length);
        console.log(sn)
        wx.navigateTo({
          url: '/subpage/pages/charge/charge?sn=' + sn,
        })
      }
    })
  },
  viewRate(){
    this.setData({
      show: true
    })
  },
  //费率列表
  getRate(id){
    let that = this
    let thisTime =new Date().getTime()
    let dates = formatTime(new Date())
    let res = wx.request({
      url: that.data.baseUrl+'/iot/rates/site/'+id,
      method:'GET',
      success(result){
        console.log('shuju',result)
        var current ='', flag 
        if(result.data.code == 0){
          let list = result.data.list
          let data = result.data.list
          let some = data.map((item, index) => {
            item.begin_time =item.beginTime 
            item.end_time = item.endTime 
            item.coupon = item.service - (item.service * item.discount)
            item.total = (item.electric + item.service - item.discount).toFixed(3) 
            item.beginTime = new Date(dates+' '+item.beginTime).getTime()
            if(item.endTime == '00:00:00'){
              item.endTime = new Date(dates+' '+'23:59:59').getTime()
            }else{
              item.endTime = new Date(dates+' '+item.endTime).getTime()
            }
            
            
            return item
          })
          .filter(item => (item.beginTime < thisTime && item.endTime >= thisTime))
          let groups = {}
          let userTime = {}
          if(result.data.groups){
            if(result.data.groups.list && result.data.groups.times){
              let groupsPrice = result.data.groups.list
              let times = result.data.groups.times
              groupsPrice.map((item, index) => {
                item.begin_time =item.beginTime 
                item.end_time = item.endTime 
                item.coupon = item.service - (item.service * item.discount)
                item.total = (item.electric + item.service -item.discount).toFixed(3)
                item.beginTime = new Date(dates+' '+item.beginTime).getTime()
                item.endTime = new Date(dates+' '+item.endTime).getTime()
                if(item.beginTime <= thisTime && item.endTime >= thisTime){
                  localIndex = index
                }
              })
              
              if(result.data.groups){
              userTime = result.data.groups.times
              }
            }
          }
          console.log('eeeeeeeee11',some)
          that.setData({
            rate: some[0]
          })
          
        }
      }
    })
    
    
  },
  //
  getCompanyRate(id){
    let that = this
    let thisTime =new Date().getTime()
    let dates = formatTime(new Date())
    let res = service("GET", '/iot/rates/site/'+id). then(result => {
      if(result.data.code ==0){
        let list = result.data.list
        let data = result.data.list
        let confirmRate = {}
        let some = data.map((item, index) => {
          item.begin_time =item.beginTime 
          item.end_time = item.endTime 
          item.coupon = item.service - (item.service * item.discount)
          // item.total = (item.electric + item.service - item.discount).toFixed(3) 
          item.beginTime = new Date(dates+' '+item.beginTime).getTime()
          if(item.endTime == '00:00:00'){
            item.endTime = new Date(dates+' '+'23:59:59').getTime()
          }else{
            item.endTime = new Date(dates+' '+item.endTime).getTime()
          }
          return item
        })
        .filter(item => (item.beginTime < thisTime && item.endTime >= thisTime))
        console.log('eeeeeeeee11',some)
        let localIndex = {}
        
        if(result.data.groups){
          if(result.data.groups.list && result.data.groups.times){
            let groupsPrice = result.data.groups.list
            let times = result.data.groups.times
            groupsPrice.map((item, index) => {
              item.begin_time =item.beginTime 
              item.end_time = item.endTime 
              item.coupon = item.service - (item.service * item.discount)
              item.total = (item.electric + item.service -item.discount).toFixed(3)
              if(item.endTime == '00:00:00'){
                item.endTime = new Date(dates+' '+'23:59:59').getTime()
              }else{
                item.endTime = new Date(dates+' '+item.endTime).getTime()
              }
              item.beginTime = new Date(dates+' '+item.beginTime).getTime()
              if(item.beginTime <= thisTime && item.endTime >= thisTime){
                localIndex = item
              }
              return item
            })
            if(localIndex.beginTime){
              let confirm = times.map((item, index) => {
                item.beginTime = new Date(dates+' '+item.beginTime).getTime()
                item.endTime = new Date(dates+' '+item.endTime).getTime()
                if(item.beginTime <= localIndex.beginTime && item.endTime >= localIndex.endTime){
                }else{
                  localIndex = {}
                }
              })
              if(localIndex){ confirmRate = localIndex}
            }
            
            console.log('groupsPrice', localIndex, times, localIndex)
          }
        }
        that.setData({
          rate: some[0],
          confirmRate: confirmRate
        })
      }
    })
    },
        //附近站点
  nearSite() {
    let that = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log('我访问了地图', res)
        that.setData({
          lat: res.latitude,
          lng: res.longitude,
        })
        that.getSite()
      },
    })
  },
     //获取个人信息
    getusers(){
      let that = this
      let data = service('GET','/user/info',{}).then( res => {
       console.log('我获取了我的头像',res)
       if( res.data.code==0){
        that.setData({
          isVip: res.data.user.isVip
        })
       }
     })
   },
  //详情
  getSite(){
  let that = this
  let res = service("POST", '/iot/info', {id: that.data.siteId, lat: that.data.lat, lng: that.data.lng}).then(result => {
    result.data.info.distance = (result.data.info.distance/ 1000).toFixed(1)
    that.setData({
      site: result.data.info
    })
    that.getGunList()
    that.getParking()
  })
  },
    //详情
    getParking(){
      let that = this
      let res = service("GET", '/parking/seat/'+this.data.siteId).then(result => {
        console.log('result',result)
        that.setData({
          overPrice: result.data.seat
        })
      })
      },
      onClose() {
        this.setData({ show: false });
      },
      onCloseGun() {
        this.setData({ showGunList: false });
      },
       //充电设备状态列表
       getGunList(resh){
        // this.setData({
        //   showGunList: true
        // })
        let that = this
       
        let res = wx.request({
          url: that.data.baseUrl+'/iot/guns/'+that.data.site.id,
          method:'GET',
          success(result){
            console.log('数据',result)
            if(result.data.code == 0){
              let list = result.data.list
              let thisTime =new Date().getTime()
              let dates = formatTime(new Date())
              // let data = result.data.list
              // let some = data.map(item => {
              //   item.begin_time =item.beginTime 
              //   item.end_time = item.endTime 
              //   item.coupon = item.service - (item.service * item.discount)
              //   item.total = item.electric + item.service 
              //   item.beginTime = new Date(dates+' '+item.beginTime).getTime()
              //   item.endTime = new Date(dates+' '+item.endTime).getTime()
              //   return item
              // })
              // .filter(item => (item.beginTime <= thisTime && item.endTime >= thisTime))
             
              let totalGun = list.length
              console.log('list', list, totalGun)
              that.setData({
                gunList:list,
                totalGun: totalGun
                // rate: some[0]
              })
              if(resh){
                wx.stopPullDownRefresh()
              }
              
            }
          }
        })
      },
        //导航
  navi_btn: function (e) {
    console.log('导航', e)
    let lng = e.currentTarget.dataset.lng;
    let lat = e.currentTarget.dataset.lat;
    // var _gcj02 = util.bd09Togcj02(lng, lat);
    let address = e.currentTarget.dataset.address;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.openLocation({
          latitude:Number(lat),
          longitude: Number(lng),
          name: address,
          scale: 16, //缩放比例为18
        })
      },
    })
  },
  goNoor(e){
    console.log('导航', e)
    let lng = e.currentTarget.dataset.lng;
    let lat = e.currentTarget.dataset.lat;
    wx.switchTab({
      url: `/pages/mapsearch/mapsearch?lng=${lng}&lat=${lat}`,
    })
  },
})